<template>
  <el-table
    ref="xklTable"
    :data="dataList"
    border
    :class="'xklTable' + tableId"
    :row-key="$attrs.rowkey ||'id'"
    v-if="reFresh"
    :header-cell-style="{backgroundColor: '#3698ce', color: '#ffffff', letterSpacing: '2px', fontSize: '16px'}"
    v-bind='$attrs'
    v-on="$listeners"
    v-loading="$attrs.dataListLoading"
    @sort-change="sortChangeHandle"
    element-loading-text="拼命加载中"
    style="width: 100%;margin-bottom: 20px">
    <slot name="selection"></slot>
    <el-table-column class-name="selectBox" :reserve-selection="$attrs.reserve" :selectable='$attrs.selectable' v-if="$attrs.selection" type="selection"  width="60" header-align="center" align="center">
    </el-table-column>
    <el-table-column class-name="indexBox" v-if="$attrs.index" type="index" width="60" align="center" label="No.">
    </el-table-column>
    <template v-for="(item, index) in fixedCol.filter(res => res[0] !== 'OPERATION')">
      <slot v-if="dropCol[index] && dropCol[index][4]" :name="dropCol[index] && dropCol[index][0]"></slot>
      <el-table-column
        v-else-if="dropCol[index] && dropCol[index][3]"
        :prop="dropCol[index] && dropCol[index][0]"
        :label="item[1]"
        :width="dropCol[index] && dropCol[index][2]"
        :key="index + tableId"
        header-align="center"
        sortable
        align="center" >
        <template  slot-scope="{ row }">
          <slot :name="dropCol[index] && dropCol[index][0]" :row="row"></slot>
        </template>
      </el-table-column>
      <el-table-column
        v-else
        :prop="dropCol[index] && dropCol[index][0]"
        :label="item[1]"
        :min-width="dropCol[index] && dropCol[index][2]"
        :key="index + tableId"
        header-align="center"
        show-overflow-tooltip
        sortable
        align="center">
      </el-table-column>
    </template>
    <el-table-column v-if="fixedCol.some(res => res[0] === 'OPERATION')" fixed="right" label="操作" :width="fixedCol[fixedCol.length - 1][1]" header-align="center" align="center" >
      <template slot-scope="{ row }">
        <slot name="operation" :row="row"></slot>
      </template>
    </el-table-column>
  </el-table>
</template>
<script>
  import Sortable from 'sortablejs'
  export default {
    name: 'xklTable',
    props: {
      tableColumn: {
        type: Array,
        required: true
      },
      dataList: {
        type: Array,
        required: true
      }
    },
    data () {
      return {
        sortable: null,
        dropCol: [],
        fixedCol: [],
        reFresh: true,
        sort: true,
        dragDisabledFlag: false,
        tableId: '',
        pageId: '',
        userId: ''
      }
    },
    watch: {
      // tableColumn () {
      //   this.init()
      // }
    },
    computed: {
      delIndex () {
        return Boolean(this.$attrs.index) + Boolean(this.$attrs.selection)
      }
    },
    mounted () {
      this.fixedCol = JSON.parse(JSON.stringify(this.tableColumn))
      this.dropCol = JSON.parse(JSON.stringify(this.tableColumn))
      this.init()
    },
    methods: {
      init () {
        this.pageId = this.$route.name
        this.userId = this.$store.state.user.id
        this.tableId = this.$refs.xklTable && this.$refs.xklTable._uid
        this.getColumn()
      },
      // 列拖拽
      columnDrop () {
        const _this = this
        const wrapperTr = document.querySelector(`.xklTable${this.tableId} .el-table__header-wrapper tr`)
        wrapperTr && wrapperTr.querySelectorAll('th').forEach(el => {
          el.oncontextmenu = () => false;
        })
        wrapperTr && _this.sortCreate(wrapperTr)
      },
      sortCreate (wrapperTr) {
        this.sortable = Sortable.create(wrapperTr, {
          animation: 180,
          delay: 0,
          forceFallback: true,
          disabled: false,
          filter: '.selectBox, .indexBox',
          onEnd: evt => {
            const oldItem = this.dropCol[evt.oldIndex - this.delIndex]
            this.dropCol.splice(evt.oldIndex - this.delIndex, 1)
            this.dropCol.splice(evt.newIndex - this.delIndex, 0, oldItem)
            this.saveColumn()
          },
          onMove: evt => {
            if (evt.related.cellIndex < this.delIndex) {
              return false
            }
          }
        })
      },
      // 排序
      sortChangeHandle ({ column, prop, order }) {
        this.$emit('sortChange', column, prop, order)
      },
      // 获取列表字段
      getColumn () {
        this.$http({
          url: this.$http.adornUrl('/proxyKpiApi/sys/sysPageColumn/get'),
          method: 'post',
          data: this.$http.adornData({
            userId: this.userId,
            pageId: this.pageId,
            tableId: this.$attrs.tableId || 'representTableID'
          }, false)
        }).then(({data}) => {
          if (data && data.code === 0) {
            if (data.column && data.column.tableColumn) {
              this.fixedCol = JSON.parse(data.column.tableColumn)
              this.dropCol = JSON.parse(data.column.tableColumn)
              this.reFresh = false
              this.$nextTick(() => {
                this.reFresh = true
              })
            }
            setTimeout(() => { this.columnDrop() }, 500)
          }
        })
      },
      // 保存新的排序
      saveColumn () {
        this.$http({
          url: this.$http.adornUrl('/proxyKpiApi/sys/sysPageColumn/addOrUpdate'),
          method: 'post',
          data: this.$http.adornData({
            userId: this.userId,
            pageId: this.pageId,
            tableId: this.$attrs.tableId || 'representTableID',
            tableColumn: JSON.stringify(this.dropCol)
          }, false)
        }).then(({data}) => {
          if (data && data.code === 0) {
            // this.getColumn()
          }
        })
      }
    }
  }
</script>
<style lang="less" scoped>

</style>
